import requests
from application.config.redis import connect_redis, redis_exists, redis_get, redis_set

'''
    微信access_token获取
    有点像普通token,两个小时可用，每天最多请求5000次
'''


def get_access_token():
    url = "https://api.weixin.qq.com/cgi-bin/token"
    # params = {  # 一汽丰田小程序
    #     "grant_type": "client_credential",
    #     "appid": "wx2cbba5931ada9e5d",
    #     "secret": "0d440eedd1a829cf563a3a27d9d523c8",
    # }
    params = {  # 一c小程序
        "grant_type": "client_credential",
        "appid": "wx9adbf602b47906c2",
        "secret": "72764c203f6ba16e399ad4cedb60dd8e",
    }
    # params = {  # 一汽丰田公众号
    #     "grant_type": "client_credential",
    #     "appid": "wxcd2c61ec90a2529c",
    #     "secret": "d889931ea59561896de0402d18843dc9",
    # }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        data = response.json()
        # data = {
        #     "access_token": "WD3AarpeyM/Vajl7/qIMBQ==",
        #     "expires_in": "ok9HS5Shggvu6AUSIyz8jQQ_QX6k"
        # }
        # access_token = data['access_token']
        # expires_in = data['expires_in']
        return data
    else:
        return False


def get_access_token_gzh():
    url = "https://api.weixin.qq.com/cgi-bin/token"
    params = {  # 一汽丰田公众号
        "grant_type": "client_credential",
        "appid": "wxcd2c61ec90a2529c",
        "secret": "d889931ea59561896de0402d18843dc9",
    }
    # params = {  # 一C公众号
    #     "grant_type": "client_credential",
    #     "appid": "wx0a766dde54c6c5e6",
    #     "secret": "4ca7dbe10ebbce11f8b61eb92bbd2ddb",
    # }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        data = response.json()
        # data = {
        #     "access_token": "WD3AarpeyM/Vajl7/qIMBQ==",
        #     "expires_in": "ok9HS5Shggvu6AUSIyz8jQQ_QX6k"
        # }
        # access_token = data['access_token']
        # expires_in = data['expires_in']
        return data
    else:
        return False


# 获取redis中的access_token
def redis_access_token():
    if redis_exists(1, 'access_token'):
        return redis_get(1, 'access_token').decode('utf-8')
    else:
        access_token = get_access_token()['access_token']  # 生成新的access_token
        redis_set(1, 3600, 'access_token', access_token)  # 过期时间3600秒
        return access_token


# 获取redis中的access_token
def redis_access_token_gzh():
    if redis_exists(0, 'access_token'):
        return redis_get(0, 'access_token').decode('utf-8')
    else:
        access_token = get_access_token_gzh()['access_token']  # 生成新的access_token
        redis_set(0, 3600, 'access_token', access_token)  # 过期时间3600秒
        return access_token
